<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" @submit.native.prevent>
      <el-form-item label="账号">
        <el-input size="small" v-model="listQuery.q_name" maxlength="20"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="small" type="primary" @click="check">查询</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="button-table-margin">
      <el-button size="small" type="primary" @click='addAdmin' v-permission="['admin/system/adminuser/save']">添加
      </el-button>
      <el-button size="small" type="primary" @click='editAdmin' v-permission="['admin/system/adminuser/update']">修改
      </el-button>
      <el-button size="small" type="primary" @click='del' v-permission="['admin/system/adminuser/del']">删除</el-button>
      <el-button size="small" type="primary" @click='freeze' v-permission="['admin/system/adminuser/freeze']">冻结
      </el-button>
    </div>
    <el-table ref="singleTable" :data="dataList" v-loading="listLoading" border fit highlight-current-row
      style="width: 100%" @current-change="handleCurrentChange">
      <el-table-column type="index" align="center" width="50">
      </el-table-column>
      <el-table-column property="name" label="账号" show-overflow-tooltip>
      </el-table-column>
      <el-table-column label="角色" property="roleName" show-overflow-tooltip>
      </el-table-column>
      <el-table-column property="tel" label="电话">
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ codeBox.ADMIN_STATUS[scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column property="createTime" width="200" label="创建时间">
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />
    <el-dialog :title="judgmentTitle" :visible.sync="dialogFormVisible" width="70%">
      <div class="app-container">
        <el-row>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"
            class="demo-ruleForm el-form-bottom">
            <el-col :span="24">
              <el-form-item label="账号" prop="name">
                <el-input v-model="ruleForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="showPassword">
              <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-else>
              <el-form-item label="密码">
                <el-input v-model="ruleForm.password"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="电话" prop="tel">
                <el-input v-model="ruleForm.tel"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="ruleForm.status">
                  <el-radio v-for="item in statesList" :key="item.value" :label="item.value">{{item.name}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="选择角色" prop="roleId">
                <el-select v-model="ruleForm.roleId" placeholder="请选择" style="width: 323.06px">
                  <el-option v-for="item in roles" :label="item.rolesName" :key="item.id" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    fetchAdminList,
    delAdmin,
    freezeAdmin,
    toAddAdmin,
    saveAdmin,
    toEditAdmin,
    updateAdmin
  } from '@/api/system'
  import {
    getCodeManager,
    codeToArray
  } from '@/api/all'
  import Pagination from '@/components/Pagination'
  import {
    Message
  } from 'element-ui'
  import Tinymce from '@/components/Tinymce'
  export function isvalidPhone(str) {
    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
    return reg.test(str)
  }
  export default {
    name: 'adminuserlist',
    components: {
      Tinymce
    },
    components: {
      Pagination
    },
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '' && this.judgmentType == '1') {
          callback(new Error('请输入密码'));
        } else {
          if ((value != '') && (value.length < 6 || value.length > 20)) {
            callback(new Error('请输入6-20位密码'));
          }
          callback();
        }
      };
      var validPhone = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入电话'))
        } else if (!isvalidPhone(value)) {
          callback(new Error('请输入正确的11位手机号码'))
        } else {
          callback()
        }
      }
      return {
        dataList: [],
        adminStatus: [],
        total: 0,
        listLoading: false,
        listQuery: {
          page: 1,
          limit: 20,
          q_name: ''
        },
        currentRow: null,
        showPassword: true, // 新增是显示密码，编辑是隐藏
        judgmentTitle: '管理员添加',
        judgmentType: '1',
        dialogFormVisible: false,
        statesList: [],
        roles: [],
        ruleForm: {
          name: "",
          password: '',
          status: "",
          tel: '',
          roleId: ""
        },
        rules: {
          name: [{
              required: true,
              message: "请输入账号",
              trigger: "blur"
            },
            {
              max: 20,
              message: '不能超过20个字符',
              trigger: 'blur'
            }
          ],
          password: [{
            validator: validatePass,
            required: true,
            trigger: "blur"
          }],
          status: [{
            required: true,
            message: "请选择状态",
            trigger: "change"
          }, ],
          tel: [{
            validator: validPhone,
            required: true,
            trigger: "blur"
          }, ],
          roleId: [{
            required: true,
            message: "请选择角色",
            trigger: "change"
          }]
        },
      }
    },
    created() {
      getCodeManager('ADMIN_STATUS', () => {
        this.adminStatus = codeToArray('ADMIN_STATUS');
        this.statesList = codeToArray("ADMIN_STATUS");
      })
      toAddAdmin().then(res => {
        this.roles = res.data.data.roles
      })
      this.getList()
    },
    methods: {
      handleCurrentChange(val) {
        // 选中当前行数据
        this.currentRow = val
      },
      // 获取列表数据
      getList() {
        this.listLoading = true
        fetchAdminList(this.listQuery).then(response => {
          this.dataList = response.data.rows
          this.total = response.data.total
          this.listLoading = false
          console.log(this.dataList)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      check() {
        this.getList()
      },
      reset() {
        this.listQuery = {
          page: 1,
          limit: 20,
          q_name: ''
        }
        this.getList()
      },
      addAdmin() {
        this.showPassword = true
        this.judgmentTitle = '管理员添加'
        this.judgmentType = '1'
        this.dialogFormVisible = true;
        this.resetForm('ruleForm')
      },
      editAdmin() {
        if (!this.currentRow) {
          Message.error('请选择操作行。')
          return;
        };
        this.showPassword = false
        this.judgmentTitle = '管理员编辑'
        this.judgmentType = '2'
        this.dialogFormVisible = true;
        toEditAdmin({
          id: this.currentRow.id
        }).then(res => {
          this.ruleForm = res.data.data.admin
          this.ruleForm.status = this.ruleForm.status + ""
          this.ruleForm.password = ""
        })
      },
      freeze() {
        if (!this.currentRow) {
          Message.error('请选择操作行。')
          return;
        };
        if (this.currentRow.status == 2) {
          Message.error('此账号已被冻结。')
          return;
        }
        if (this.currentRow.status == 3) {
          Message.error('此账号已被删除，不能进行冻结操作。')
          return;
        }
        this.$confirm('确定冻结吗？', '提示', {
          onfirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          freezeAdmin({
            id: this.currentRow.id
          }).then(res => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: '冻结成功!'
              });
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: res.data.message
              });
            }
          })
        })
      },
      del() {
        if (!this.currentRow) {
          Message.error('请选择操作行。')
          return;
        };
        if (this.currentRow.status == 3) {
          Message.error('此账号已被删除。')
          return;
        }
        this.$confirm('确定删除吗？', '提示', {
          onfirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delAdmin({
            id: this.currentRow.id
          }).then(res => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: res.data.message
              });
            }
          })
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.judgmentType == '1') {
              saveAdmin(this.ruleForm).then(res => {
                if (!res.data.success) {
                  Message.error(res.data.message);
                  return;
                }
                Message.success('操作成功')
                this.dialogFormVisible = false;
                this.getList()
              })
            } else {
              let params = {
                id: this.ruleForm.id,
                name: this.ruleForm.name,
                password: this.ruleForm.password,
                status: this.ruleForm.status,
                tel: this.ruleForm.tel,
                roleId: this.ruleForm.roleId
              }
              updateAdmin(params).then(res => {
                if (!res.data.success) {
                  Message.error(res.data.message);
                  return;
                }
                Message.success('操作成功')
                this.dialogFormVisible = false;
                this.getList()
              })
            }
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      }
    }
  }
</script>
<style scoped>
  .filter-container .el-col-6 {
    margin-bottom: 15px;
  }

  .filter-item {
    margin-bottom: 0
  }

  /deep/ .filter-container label {
    font-size: 14px;
    font-weight: 500;
    margin-right: 10px;
  }
</style>
